package com.lxj.ticket.service.modules.config;

import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
public class CommonOkHttpConfig {


    /**
     * okhttp的连接池配置
     * @return
     */
    @Bean
    public ConnectionPool connectionPool() {
        return new ConnectionPool(
                100,                    // maxIdleConnections
                30, TimeUnit.MINUTES   // keepAliveDuration
        );
    }

    /**
     * 配置每个路由上的请求数
     * @return
     */
    @Bean
    public Dispatcher dispatcher() {
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.setMaxRequests(200);           // 最大并发请求数
        dispatcher.setMaxRequestsPerHost(50);     // 每个主机最大并发请求数
        return dispatcher;
    }

    /**
     * 配置okhttp的配置
     * @return
     */
    @Bean
    public OkHttpClient okHttpClient() {
        return new OkHttpClient.Builder()
                .connectionPool(connectionPool())
                .dispatcher(dispatcher())
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .retryOnConnectionFailure(false)      // 连接失败重试
                .followRedirects(true)               // 跟随重定向
                .followSslRedirects(true)            // 跟随SSL重定向
                .build();
    }

}
